<!-- components/TemplateManagement.vue -->
<template>
  <div class="template-management">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreateTemplate">
        <el-icon><Plus /></el-icon>新建模板
      </el-button>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索模板..."
        style="width: 300px; margin-left: 16px"
        clearable
      >
        <template #append>
          <el-button :icon="Search" />
        </template>
      </el-input>
    </div>

    <el-table :data="filteredTemplates" style="width: 100%; margin-top: 16px">
      <el-table-column prop="title" label="模板名称" width="200" />
      <el-table-column prop="category" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getCategoryType(row.category)">
            {{ getCategoryLabel(row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="is_public" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_public ? 'success' : 'info'">
            {{ row.is_public ? '公开' : '私有' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="$emit('use-template', row)"> 使用 </el-button>
          <el-button link type="warning" @click="$emit('edit-template', row)"> 编辑 </el-button>
          <el-button link type="danger" @click="handleDeleteTemplate(row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

const api = inject('$api')

const emit = defineEmits(['edit-template', 'use-template', 'create-template'])

const templates = ref([])
const searchKeyword = ref('')

const categories = [
  { value: 'contract', label: '合同' },
  { value: 'agreement', label: '协议' },
  { value: 'petition', label: '诉状' },
  { value: 'notice', label: '通知' },
  { value: 'affidavit', label: '宣誓书' },
  { value: 'other', label: '其他' },
]

const filteredTemplates = computed(() => {
  if (!searchKeyword.value) return templates.value
  return templates.value.filter(
    (template) =>
      template.title.includes(searchKeyword.value) ||
      template.description.includes(searchKeyword.value),
  )
})

// 获取模板列表
const loadTemplates = async () => {
  try {
    const response = await api.documentTemplates.getTemplates()
    console.log('获取模板列表成功', response)

    if (response && response.data && Array.isArray(response.data.records)) {
      // 字段映射
      templates.value = response.data.records.map((item) => ({
        id: item.id,
        title: item.title,
        category: item.category || 'other',
        description: item.description || '暂无描述',
        is_public: item.isPublic === 1,
        created_at: item.createdAt,
        content: item.content,
        formSchema: item.formSchema,
      }))
      console.log('处理后的模板数据:', templates.value)
    } else {
      console.error('API 返回的数据结构不符合预期:', response)
      templates.value = []
    }
  } catch (error) {
    console.error('加载模板列表失败:', error)
    ElMessage.error('加载模板列表失败')
    templates.value = []
  }
}

// 创建模板 - 直接跳转到设计页
const handleCreateTemplate = () => {
  emit('create-template')
}

// 删除模板
const handleDeleteTemplate = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除此模板吗？', '提示', {
      type: 'warning',
    })

    await api.documentTemplates.deleteTemplate(id)
    ElMessage.success('删除成功')
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取分类标签类型
const getCategoryType = (category) => {
  const types = {
    contract: 'primary',
    agreement: 'success',
    petition: 'warning',
    notice: 'info',
    affidavit: 'danger',
    other: 'info',
  }
  return types[category] || 'info'
}

// 获取分类显示标签
const getCategoryLabel = (category) => {
  const categoryObj = categories.find((cat) => cat.value === category)
  return categoryObj ? categoryObj.label : category
}

onMounted(() => {
  loadTemplates()
})
</script>
